package com.ansion.basedb.database.sql;

import android.database.Cursor;

import androidx.annotation.NonNull;

import com.ansion.basedb.database.ISqlDataBase;
import com.ansion.log.S;
import com.ansion.log.VLog;
import com.ansion.utils.CloseUtils;

/**
 * created by zhaoyuntao
 * on 27/04/2023
 */
public abstract class DBOperation extends DBBaseOperation<ISqlDataBase> {
    private final ISqlDataBase sqLiteDatabase;

    public DBOperation(@NonNull ISqlDataBase sqLiteDatabase, @NonNull String tag, @DBOperationCode int dbOperationCode) {
        super(tag, dbOperationCode);
        this.sqLiteDatabase = sqLiteDatabase;
    }

    @Override
    final public void execute(@NonNull DBTaskState state, @NonNull SQLTransactionListener listener) {
        if (getDbOperationCode() == DBOperationCode.SELECT) {
            Cursor r = null;
            try {
                r = op(sqLiteDatabase, state);
            } catch (Throwable e) {
                VLog.e(e, "TAG_STORAGE", "query fail");
            } finally {
                CloseUtils.silentlyClose(r);
            }
        } else {
            sqLiteDatabase.beginTransactionWithListener(listener);
            try {
                op(sqLiteDatabase, state);
                sqLiteDatabase.setTransactionSuccessful();
            } catch (Throwable e) {
                VLog.e(e, "TAG_STORAGE", "execute update fail");
                S.e(e);
            } finally {
                sqLiteDatabase.endTransaction();
            }
        }


    }
}
